package org.xiaov.bean;

import java.io.Serializable;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 封装好的结果集
 * </p>
 *
 * @author xiaovcloud
 * @version：1.0
 * @since 2021/4/3 12:47
 */
public class Pair<L, R> implements Serializable {

    private static final long serialVersionUID = 4954918890077093841L;
    /**
     * key
     */
    L l;
    /**
     * value
     */
    R r;

    private Pair() {
    }

    private Pair(L l, R r) {
        this.l = l;
        this.r = r;
    }

    /**
     * 静态获取Pair对象
     *
     * @param left
     * @param right
     * @param <L>
     * @param <R>
     * @return
     */
    public static <L, R> Pair<L, R> of(L left, R right) {
        return new Pair<>(left, right);
    }

    /**
     * 静态获取Pair对象
     *
     * @param pair
     * @param <L>
     * @param <R>
     * @return
     */
    public static <L, R> Pair<L, R> of(Map.Entry<L, R> pair) {
        L left;
        R right;
        if (pair != null) {
            left = pair.getKey();
            right = pair.getValue();
        } else {
            left = null;
            right = null;
        }

        return new Pair<L, R>(left, right);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        } else if (!(obj instanceof Map.Entry)) {
            return false;
        } else {
            Map.Entry<?, ?> other = (Map.Entry) obj;
            return Objects.equals(this.getLeft(), other.getKey())
                    && Objects.equals(this.getRight(), other.getValue());
        }
    }

    public L getLeft() {
        return l;
    }

    public R getRight() {
        return r;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(this.getLeft()) ^ Objects.hashCode(this.getRight());
    }

    @Override
    public String toString() {
        return "(" + this.getLeft() + ',' + this.getRight() + ')';
    }

    public String toString(String format) {
        return String.format(format, this.getLeft(), this.getRight());
    }
}

